import styles from './index.less';
import { useState, useEffect } from 'react';
import { Card, message, Upload, Breadcrumb } from 'antd';
import { IKnowledge, IKnowledgeImg } from '@/types';
import {PlusOutlined,EditOutlined,SettingOutlined,CloudUploadOutlined,DeleteOutlined,} from '@ant-design/icons';
import {Drawer,Form,Button,Col,Row,Input,Select,Popconfirm,Switch,Tooltip,Pagination,} from 'antd';
import { KnowledgeModelState, Link, useDispatch, useSelector } from 'umi';
import CommentFoot from '@/components/commonFooter';
import Uploads from '@/components/Upload'
const { Option } = Select;
function Knowledge() {
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const dispatch = useDispatch();
  const [upurl] = useState("")
  useEffect(() => {
    dispatch({
      type: 'knowledge/getKnowledgeList',
      payload: {
        page: 1,
        pageSize: 8,
      },
    });
  }, []);
  const { knowledge, knowledgeImgList } = useSelector(
    (state: {
      knowledge: KnowledgeModelState;
      knowledgeImgList: KnowledgeModelState;
    }) => state.knowledge,
  );
  console.log(knowledge,'总数据');
  
  const [visible, setVisible] = useState(false);
  const [childrenDrawer, setchildrenDrawer] = useState(false);
  // 右侧抽屉显示隐藏
  const showDrawer = () => {
    setVisible(true);
    dispatch({
      type: 'knowledge/getKnowledgeImgList',
      payload: {
        page: 1,
        pageSize: 8,
      },
    });
  };
  // 右侧抽屉隐藏
  const onClose = () => {
    setVisible(false);
  };
  // 右侧子抽屉显示
  const showChildrenDrawer = () => {
    setchildrenDrawer(true);
  };
  // 右侧子抽屉隐藏
  const onChildrenDrawerClose = () => {
    setchildrenDrawer(false);
  };

  // 知识小册搜索功能
  let [newArr, setnewArr] = useState();
  const onFinish = (values: any) => {
    let newArr: any = [];
    knowledge[0].forEach((item: IKnowledge) => {
      if (item.title == values.name && item.status == values.state) {
        newArr.push(item);
      }
    });
    setnewArr(newArr);
  };
  // 图片搜索功能
  let [ImgArr, setImgArr] = useState();
  const onImgFinish = (values: any) => {
    let ImgArr: any = [];
    knowledgeImgList[0].forEach((item: IKnowledgeImg) => {
      if (
        item.originalname.split('.')[0] == values.filename ||
        item.originalname.split('.')[1] == values.filetype
      ) {
        console.log(item.originalname.split('.')[0]);
        ImgArr.push(item);
      }
    });
    setImgArr(ImgArr);
  };

  // 上传图片
  const { Dragger } = Upload;
  const token = localStorage.getItem('token');
  let [imgUrl, setImgUrl] = useState('');
  const props = {
    name: 'file',
    multiple: true,
    action: 'https://creationapi.shbwyz.com/api/file/upload?unique=0',
    headers: { Authorization: `Bearer ${token}` },
    showUploadList: true,
    onChange(info: {
      file: { name?: any; status?: any; response?: any };
      fileList: any;
    }) {
      const { status } = info.file;

      if (status !== 'uploading') {
        console.log(info.file, info.fileList);
      }

      if (status === 'done') {
        // 上传成功
        message.success(`${info.file.name} file uploaded successfully.`);
        setImgUrl(info.file.response.data.url);
      } else if (status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
    onDrop(e: { dataTransfer: { files: any } }) {
      console.log('Dropped files', e.dataTransfer.files);
    },
  };

  // 选择图片
  const changeImg = (url: string) => {
    setImgUrl(url);
    setchildrenDrawer(false);
  };
  // 创建文件
  const onCreate = (createObj: any) => {
    dispatch({
      type: 'knowledge/upload',
      payload: {
        cover: imgUrl,
        isCommentable: createObj.isCommentable,
        summary: createObj.summary,
        title: createObj.title,
      },
    });
    setVisible(false);
  };

  // 修改文件
  let [title, setTitle] = useState('');
  const changeFile = (item: any) => {
    console.log(item);
    dispatch({
      type: 'knowledge/getKnowledgeImgList',
      payload: {
        page: 1,
        pageSize: 8,
      },
    });
    setVisible(true);
    setTitle(item.title);
    form1.setFieldsValue({ title: item.title, summary: item.summary });
    setImgUrl(item.cover);
    setChecked(item.isCommentable);
  };
  // 切换
  let [checked, setChecked] = useState(false);
  const onChange = (checked: boolean) => {
    setChecked(checked);
  };
  // 删除功能
  function confirm(id: string) {
    dispatch({
      type: 'knowledge/KnowledgeDelete',
      payload: id,
    });
  }
  // 取消删除
  function cancel(e: any) {
    console.log(e);
    message.error('Click on No');
  }
  // 更改状态功能
  let [state, setState] = useState('publish');
  const onState = (id: string) => {
    if (state == 'publish') {
      setState('draft');
    } else {
      setState('publish');
    }
    console.log(state);

    dispatch({
      type: 'knowledge/KnowledgeState',
      payload: { id, state },
    });
  };
  // 分页功能
  const changePage = (page: number, pageSize: number) => {
    dispatch({
      type: 'knowledge/getKnowledgeList',
      payload: {
        page,
        pageSize,
      },
    });
  };

  // 右侧分页功能
  const changeChildrenPage = (page: number, pageSize: number) => {
    dispatch({
      type: 'knowledge/getKnowledgeImgList',
      payload: {
        page,
        pageSize,
      },
    });
  };
  return (
    <div className={styles.Knowledge}>
      {/* 头部面包屑 */}
      <div className={styles.Knowledge_head}>
        <Breadcrumb>
          <Breadcrumb.Item>
            <a href="/">工作台</a>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <a href="">页面管理</a>
          </Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <div className={styles.Knowledge_body}>
          {/* 知识小册搜索框 */}
        <div className={styles.Knowledge_search}>
            <Form  form={form}  name="advanced_search"  className={styles.ant_advanced_search_form}  onFinish={onFinish}>
                <Row gutter={24}>
                <Col className={styles.search_input}>
                    <Form.Item
                    className={styles.search_input_Item}
                    name={'name'}
                    label={`名称`}
                    >
                    <Input placeholder="请输入知识库名称" />
                    </Form.Item>
                    <Form.Item name={`state`} label={`状态`}>
                    <Select style={{ width: 100 }}>
                        <Option value="publish">已发布</Option>
                        <Option value="draft">草稿</Option>
                    </Select>
                    </Form.Item>
                </Col>
                </Row>
                <Row>
                <Col span={24} style={{ textAlign: 'right' }}>
                    <Button type="primary" htmlType="submit">
                    搜索
                    </Button>
                    <Button
                    style={{ margin: '0 8px' }}
                    onClick={() => {
                        form.resetFields();
                    }}
                    >
                    重置
                    </Button>
                </Col>
                </Row>
            </Form>
        </div>
        <div className={styles.Knowledge_main}>
          <div className={styles.Knowledge_main_header}>
            <div></div>
            {/* 新建按钮 */}
            <div>
              <Button onClick={showDrawer} type="primary">
                <PlusOutlined /> 新建
              </Button>
            </div>
            <Drawer placement="right" onClose={onClose} visible={visible}>
              <Form form={form1} name="advanced_create" onFinish={onCreate}>
                <Drawer
                  width={620}
                  onClose={onClose}
                  visible={visible}
                  bodyStyle={{ paddingBottom: 80 }}
                  footer={
                    <Col span={24} style={{ textAlign: 'right' }}>
                      <Button
                        onClick={() => {
                          form1.resetFields();
                        }}
                      >
                        取消
                      </Button>
                      <Button
                        type="primary"
                        onClick={() => {
                          form1.submit();
                        }}
                      >
                        创建
                      </Button>
                    </Col>
                  }
                  footerStyle={{ marginRight: 0 }}
                >
                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item
                        name={'title'}
                        label={'名称'}
                        rules={[
                          {   message: 'Please enter user name' },
                        ]}
                      >
                        <Input
                          value={title}
                          onChange={(e) => {
                            setTitle(e.target.value);
                          }}
                        />
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item
                        name={'summary'}
                        label={'描述'}
                        rules={[
                          {   message: 'Please enter user name' },
                        ]}
                      >
                        <Input />
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item name={'isCommentable'} label={'评论'}>
                        <Switch checked={checked} onChange={onChange} />
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item
                        name={'cover'}
                        label={'封面'}
                        rules={[
                          {
                             
                            message: 'please enter url description',
                          },
                        ]}
                      >
                        <div className={styles._fileOss}>
                          <Uploads upurl={upurl}/>
                        </div>
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item>
                        <Input value={imgUrl} />
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={16} style={{ marginBottom: 100 }}>
                    <Col span={24}>
                      <Button onClick={showChildrenDrawer}>选择文件</Button>
                      {imgUrl ? (
                        <Button
                          danger
                          onClick={() => {
                            setImgUrl('');
                          }}
                        >
                          移除
                        </Button>
                      ) : null}
                    </Col>
                  </Row>
                </Drawer>
              </Form>
              <Drawer
                title="文件选择"
                width={720}
                closable={false}
                onClose={onChildrenDrawerClose}
                visible={childrenDrawer}
              >
                <div className={styles.Knowledge_childrenSearch}>
                  <Form
                    form={form2}
                    name="advanced_search"
                    className={styles.ant_advanced_search_form}
                    onFinish={onImgFinish}
                  >
                    <Row gutter={24}>
                      <Col className={styles.search_input}>
                        <Form.Item
                          className={styles.search_input_Item}
                          name={'filename'}
                          label={`文件名称`}
                        >
                          <Input placeholder="请输入文件名称" />
                        </Form.Item>
                        <Form.Item name={`filetype`} label={`文件类型`}>
                          <Input placeholder="请输入文件类型" />
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={24} style={{ textAlign: 'right' }}>
                        <Button type="primary" htmlType="submit">
                          搜索
                        </Button>
                        <Button
                          style={{ margin: '0 8px' }}
                          onClick={() => {
                            form2.resetFields();
                          }}
                        >
                          重置
                        </Button>
                      </Col>
                    </Row>
                  </Form>
                </div>
                <div className={styles.Knowledge_childrenMain}>
                  {knowledgeImgList[0]
                    ? (ImgArr ? ImgArr : knowledgeImgList[0]).map(
                        (item: any) => {
                          return (
                            <Card
                              onClick={() => {
                                changeImg(item.url);
                              }}
                              key={item.id}
                              className={styles.Knowledge_childrenMain_Card}
                              hoverable
                            >
                              <img alt="example" src={item.url} />
                              <div className={styles.ant_card_body}>
                                <p>{item.originalname}</p>
                              </div>
                            </Card>
                          );
                        },
                      )
                    : null}
                </div>
              </Drawer>
            </Drawer>
          </div>
          {/* 下面详情 */}
          <div className={styles.Knowledge_main_main}>
            {knowledge[0]
              ? (newArr ? newArr : knowledge[0]).map((item: IKnowledge) => {
                  return (
                    //   每一个小卡片
                    <div className={styles.Knowledge_main_Card} key={item.id} style={{paddingLeft:8, paddingRight:8,}}>
                        <div key={item.id} style={{flex:'1 1 auto',margin:'10px 0',border:' 1px solid #f0f0f0'}}>
                            <img alt="example" src={item.cover} />
                            <div className={styles.ant_card_body}>
                                <p>{item.title}</p>
                                <p>{item.summary}</p>
                            </div>
                            <ul>
                                <li style={{width:'25%'}}>
                                {' '}
                                <Link  style={{ color: 'black' }}  to={`/knowledge/editor/${item.id}`}>
                                    <EditOutlined />
                                </Link>
                                </li>
                                <li onClick={() => {   onState(item.id); }} style={{width:'25%'}}>
                                    <Tooltip title={state == 'publish' ? '设为草稿' : '发布线上'} >
                                        <CloudUploadOutlined />
                                    </Tooltip>
                                </li>
                                <li  onClick={() => {changeFile(item)}} style={{width:'25%'}}>
                                    <SettingOutlined />
                                </li>
                                <li style={{width:'25%'}}>
                                    <Popconfirm  title="确认删除?"  onConfirm={() => {confirm(item.id)}}  onCancel={cancel}  okText="确认"  cancelText="取消">
                                        <DeleteOutlined />
                                    </Popconfirm>
                                </li>
                            </ul>
                        </div>
                    </div>
                  );
                })
              : null}
          </div>
          {/* 分页 */}
          <Col span={24} style={{ textAlign: 'right', marginTop: 20 }}>
            <Pagination  pageSizeOptions={[8, 12, 24, 36]}  defaultPageSize={12}  defaultCurrent={1}  onChange={changePage}  showSizeChanger={true}  showTotal={function () {    return `共${knowledge[1]}条`;  }}/>
          </Col>
        </div>
        {/* 底部logo */}
        <CommentFoot />
      </div>
    </div>
  );
}

export default Knowledge;
